package com.tdzh.maimaiti.view;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tdzh.maimaiti.R;
import com.tdzh.maimaiti.biz.GetContractList;
import com.tdzh.maimaiti.util.UriAPI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;


import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ContractListActivity extends Activity {


    private AsyncTask mAddFriend;
    private ListView mContractList;
    private Button mSendInvitation;
    private String userphone;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_contract_list);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        mContractList = (ListView) findViewById(R.id.addfriend);
        mSendInvitation = (Button) findViewById(R.id.invite);

        SharedPreferences user = getSharedPreferences("account",0);
        userphone = user.getString("name", null);
        ContentResolver cr = getContentResolver();
        // list = GetContractList.resolveContractsList
        String phoneList = GetContractList.GetContractListString(cr, userphone);

        if (!phoneList.equals("")) {
            mAddFriend = new GetFriendsTask(phoneList,UriAPI.HTTPContract );
            System.out.println("任务启动1 ");
            mAddFriend.execute((Void) null);
           // System.out.println("任务启动2 ");
        }

        mSendInvitation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = userphone;

                for(int i = 0; i < mContractList.getCount(); i++){
                    System.out.println("开始遍历");
                    RelativeLayout layout = (RelativeLayout) mContractList.getChildAt(i);
                    CheckBox checkBox = (CheckBox) layout.findViewById(R.id.checkBox);
                    TextView phoneText = (TextView) layout.findViewById(R.id.phonenumber);
                    TextView nameText = (TextView) layout.findViewById(R.id.name);
                    System.out.println(nameText.getText());
                   // System.out.println("");
                    if(checkBox.isChecked()){
                        System.out.println("选择了一个好友");
                        phone += phoneText.getText();
                    }
                    
                }
                mAddFriend = new GetFriendsTask(phone,UriAPI.HTTPInvite);
                System.out.println("任务启动2 ");
                mAddFriend.execute((Void) null);
               // System.out.println("任务启动2 ");
            }
        });
    }


        public class GetFriendsTask extends AsyncTask{

            private final String mList;
            private final String mUrl;

            GetFriendsTask(String list,String url) {
                mList = list;
                mUrl = url;
            }

            @Override
            protected Object doInBackground(Object... params) {
               String result = "";

                //请求数据
                HttpPost httpRequest = new HttpPost(mUrl);
                byte[] data = new byte[2048];
                System.out.println(mList);
                try {
                    //创建参数

                    //JSONArray jsonArray = new JSONArray(( (  (ArrayList<Map<String,Object>>) params[0]).toString()));
                    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                    nameValuePair.add(new BasicNameValuePair("ContractList", mList));
                    System.out.println("已启动 ");
                    //对提交数据进行编码
                    httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair
                            , HTTP.UTF_8));
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    //获取响应服务器的数据
                    System.out.println("连接 " + httpResponse.getStatusLine().getStatusCode());
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {

                        //先把从服务端来的数据转化成字节数组
                        data = EntityUtils.toByteArray((HttpEntity) httpResponse.getEntity());
                        //再创建字节数组输入流对象
                        ByteArrayInputStream bais = new ByteArrayInputStream(data);
                        //绑定字节流和数据包装流
                        DataInputStream dis = new DataInputStream(bais);
                        //将字节数组中的数据还原成原来的各种数据类型，代码如下：
                        result = new String(dis.readUTF());
                        //inStream.close();
                        System.out.println("result 第二次" + result);
                        //Log.i("服务器返回信息:", result);
                        //return data;
                        //

                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(Object result) {
                mAddFriend = null;
                List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
               String r = result.toString();
                try {
                    list2 = GetContractList.resolveContractsList(r);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                if (list2 != null) {
                    System.out.println("result " + r);

                    SimpleAdapter adapter = new SimpleAdapter(ContractListActivity.this, list2, R.layout.contract_item,
                    new String[]{"name", "phoneNumber", "image"},
                    new int[]{R.id.name, R.id.phonenumber, R.id.img});
                    mContractList.setAdapter(adapter);

                } else{

                    Toast.makeText(ContractListActivity.this, "发送成功", Toast.LENGTH_SHORT);
                    //Intent intent = new Intent(MyP,);

                }
            }

        }


}